<template>
  <div class="panel right-top">
    <div class="content" ref="chartRef"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

// 模拟数据
const generateData = () => {
  const devices = [
    { name: '灌溉设备', total: 50 },
    { name: '温控设备', total: 30 },
    { name: '光照设备', total: 40 },
    { name: '监测设备', total: 60 },
    { name: '施肥设备', total: 25 }
  ]
  
  return devices.map(device => ({
    ...device,
    normal: Math.floor(device.total * (0.8 + Math.random() * 0.2)), // 80-100%正常
    warning: Math.floor(device.total * (Math.random() * 0.1)),      // 0-10%警告
    error: Math.floor(device.total * (Math.random() * 0.1))         // 0-10%故障
  }))
}

const initChart = () => {
  try {
    if (!chartRef.value) {
      console.error('图表容器未找到')
      return
    }
    
    if (chartRef.value.clientHeight === 0) {
      console.error('图表容器高度为0')
      return
    }

    if (chart) {
      chart.dispose()
    }
    
    if (chartRef.value.offsetParent === null) {
      console.error('图表容器不可见')
      return
    }

    chart = echarts.init(chartRef.value)
    const data = generateData()

    const option = {
      tooltip: {
        trigger: 'axis',
        position: function (pt: any) {
          return [pt[0], '10%'];
        },
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(51, 255, 208, 0.3)',
        borderWidth: 1,
        padding: [8, 12],
        textStyle: {
          color: '#fff'
        },
        z: 9999,
        confine: true,  // 确保悬浮窗不会超出图表区域
        formatter: (params: any) => {
          let result = `<div style="font-size: 12px; color: #33ffd0; margin-bottom: 8px; font-weight: bold;">${params[0].name}</div>`
          params.forEach((param: any) => {
            const color = param.color
            const name = param.seriesName
            const value = param.value
            result += `
              <div style="display: flex; align-items: center; margin: 4px 0;">
                <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${color}; margin-right: 8px;"></span>
                <span style="color: #fff; margin-right: 8px; min-width: 60px;">${name}</span>
                <span style="color: #33ffd0; display: flex; align-items: center; justify-content: center; min-width: 60px; font-weight: bold;">
                  ${value}台
                </span>
              </div>
            `
          })
          return result
        }
      },
      legend: {
        data: ['正常', '警告', '故障'],
        textStyle: {
          color: '#33ffd0',
          fontSize: 12
        },
        top: -2,
        itemWidth: 10,
        itemHeight: 10,
        itemGap: 15,
        padding: [5, 0, 5, 0]
      },
      grid: {
        top: '10%',
        left: '5%',
        right: '5%',
        bottom: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.map(item => item.name),
        axisLine: {
          lineStyle: {
            color: '#33ffd0',
            width: 1
          }
        },
        axisLabel: {
          color: '#33ffd0',
          fontSize: 10,
          margin: 8
        },
        axisTick: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(51, 255, 208, 0.1)',
            type: 'dashed'
          }
        },
        axisTick: {
          show: false
        }
      },
      series: [
        {
          name: '正常',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: data.map(item => item.normal),
          itemStyle: {
            color: '#2ecc71',
            borderWidth: 0
          }
        },
        {
          name: '警告',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: data.map(item => item.warning),
          itemStyle: {
            color: '#f1c40f',
            borderWidth: 0
          }
        },
        {
          name: '故障',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: data.map(item => item.error),
          itemStyle: {
            color: '#e74c3c',
            borderWidth: 0
          }
        }
      ]
    }

    chart.setOption(option)
    console.log('图表初始化成功')
  } catch (error) {
    console.error('图表初始化失败:', error)
  }
}

// 定时更新数据
let timer: number | null = null
let initTimeout: number | null = null

onMounted(async () => {
  await nextTick()

  initTimeout = window.setTimeout(() => {
    initChart()

    // 仅生成一次数据
    const data = generateData()
    if (chart) {
      try {
        chart.setOption({
          xAxis: {
            data: data.map(item => item.name)
          },
          series: [
            {
              data: data.map(item => item.normal)
            },
            {
              data: data.map(item => item.warning)
            },
            {
              data: data.map(item => item.error)
            }
          ]
        })
      } catch (error) {
        console.error('设置图表数据失败:', error)
      }
    }
  }, 300)

  window.addEventListener('resize', () => {
    if (chart) {
      try {
        chart.resize()
      } catch (error) {
        console.error('调整图表大小失败:', error)
      }
    }
  })
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  if (initTimeout) {
    clearTimeout(initTimeout)
  }
  if (chart) {
    chart.dispose()
  }
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.content {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}
</style>

